package net.dreamlu.api.oauth;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import net.dreamlu.api.util.OathConfig;
import net.dreamlu.api.util.TokenUtil;


/**
 * sina 登录 BAE
 * @author L.cm
 * @date Jun 24, 2013 10:18:23 PM
 */
public class OauthSina extends Oauth {

	private static final String AUTH_URL = "https://api.weibo.com/oauth2/authorize";
    private static final String TOKEN_URL = "https://api.weibo.com/oauth2/access_token";
    private static final String TOKEN_INFO_URL = "https://api.weibo.com/oauth2/get_token_info";
    private static final String USER_INFO_URL = "https://api.weibo.com/2/users/show.json";
	
	public OauthSina() {
		super();
		setClientId(OathConfig.getValue("openid_sina"));
		setClientSecret(OathConfig.getValue("openkey_sina"));
		setRedirectUri(OathConfig.getValue("redirect_sina"));
	}

	/**
	 * 获取授权url
	 * @param @return    设定文件
	 * @return String    返回类型
	 * @throws
	 */
	public String getAuthorizeUrl() {
		Map<String, String> params = new HashMap<String, String>();
		params.put("state", "sina");
		params.put("response_type", "code");
		params.put("client_id", getClientId());
		params.put("redirect_uri", getRedirectUri());
		return super.getAuthorizeUrl(AUTH_URL, params);
	}

	/**
	 * 获取token
	 * @param @param code
	 * @param @return    设定文件
	 * @return String    返回类型
	 * @throws
	 */
	public String getTokenByCode(String code) throws IOException{
		Map<String, String> params = new HashMap<String, String>();
		params.put("code", code);
		params.put("client_id", getClientId());
		params.put("client_secret", getClientSecret());
		params.put("grant_type", "authorization_code");
		params.put("redirect_uri", getRedirectUri());
		return TokenUtil.getAccessToken(super.doPost(TOKEN_URL, params));
	}
	
	/**
	 * 获取TokenInfo
	 * @return    设定文件
	 * @return String    返回类型
	 * @throws
	 */
	public String getTokenInfo(String accessToken) throws IOException{
		Map<String, String> params = new HashMap<String, String>();
		params.put("access_token", accessToken);
		return TokenUtil.getUid(super.doPost(TOKEN_INFO_URL, params));
	}
	
	/**
	 * 获取用户信息
	 * @param accessToken
	 * @param uid
	 * @return    设定文件
	 * @return String    返回类型
	 * @throws
	 */
	public String getUserInfo(String accessToken, String uid) throws IOException{
		Map<String, String> params = new HashMap<String, String>();
		params.put("uid", uid);
		params.put("access_token", accessToken);
		return super.doGet(USER_INFO_URL, params);
	}
	
	/**
	 * 根据code一步获取用户信息
	 * @param @param args    设定文件
	 * @return void    返回类型
	 * @throws
	 */
	public String getUserInfoByCode(String code) throws IOException{
		String accessToken = getTokenByCode(code);
		String uid = getTokenInfo(accessToken);
		return getUserInfo(accessToken, uid);
	}
}
